<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/9
 * Time: 10:14
 */

namespace App\Model\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Type extends Model
{
    protected $type;

    //类型列表
   public function typeList($pageLimit, $where = [])
   {
         $list = DB::table('type')
             ->where($where)
            ->select('t_id', 't_name',DB::raw('from_unixtime(t_create_time) AS t_create_time'), DB::raw('from_unixtime(t_update_time) AS t_update_time'))
            ->paginate($pageLimit);
         if (sizeof($list) == 0) {
            return false;
         }
       return $list;
   }
   //添加类型
    public function typeAdd($params)
    {
        return DB::table('type')->insertGetId([
            't_name'          => $params['t_name'],
            't_create_time'   => time(),
            't_update_time'   => time()
        ]);
    }
    //修改类型
    public function typeEdit($params)
    {
        return DB::table('type')->where('t_id', $params['t_id'])
            ->update([
                't_name'         =>   $params['t_name'],
                't_update_time'  =>   time()
            ]);
    }
    //删除类型
    public function typeDel($params)
    {
        $tdId = DB::table('type_detail')->where('td_tid', $params['t_id'])->value('td_id');
        if ($tdId) {
            return -1;
        }
        return DB::table('type')->where('t_id', $params['t_id'])->delete();
    }

    //获取所有的分类
    public function getAllType()
    {
        return DB::table('type')->select('t_id', 't_name')->get();
    }



    /**
     *
     * 根据单个分类获取下面所有的种类列表 存redis
     */
    public static function storageRedis($t_id)
    {
        $list = Redis::get('fenlei'.$t_id);
        if(!$list){
            $list = DB::table('type_detail')->where('td_tid', $t_id)->select('td_id', 'td_name')->get();
            Redis::set('fenlei'.$t_id,$list);
        }
        if (!is_array($list)) {
            $list = json_decode($list);
        }
        return $list;
    }

    /**
     * @param $td_id
     * @return mixed
     * 获取单个种类名称
     */
    public static function getTypeDetail($td_id){
        $name = Redis::get('zhonglei'.$td_id);
        if(!$name){
            $name  = DB::table('type_detail')->where('td_id',$td_id)->value('td_name');
            Redis::set('zhonglei'.$td_id, $name);
        }
        return $name;
    }


}